package com.childenglish.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 安全审计日志工具类
 * 记录敏感操作的详细日志
 */
public class SecurityAuditLogger {

    private static final Logger auditLogger = LoggerFactory.getLogger("SECURITY_AUDIT");
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    /**
     * 记录登录操作
     */
    public static void logLogin(String username, boolean success, String ipAddress, String userAgent) {
        String action = "LOGIN";
        String result = success ? "SUCCESS" : "FAILED";
        String message = String.format("用户登录 - 用户名: %s, 结果: %s, IP: %s", username, result, ipAddress);
        logSecurityEvent(action, username, result, message, ipAddress, userAgent);
    }

    /**
     * 记录注销操作
     */
    public static void logLogout(String username, String ipAddress, String userAgent) {
        String action = "LOGOUT";
        String message = String.format("用户注销 - 用户名: %s, IP: %s", username, ipAddress);
        logSecurityEvent(action, username, "SUCCESS", message, ipAddress, userAgent);
    }

    /**
     * 记录注册操作
     */
    public static void logRegister(String username, String role, boolean success, String ipAddress, String userAgent) {
        String action = "REGISTER";
        String result = success ? "SUCCESS" : "FAILED";
        String message = String.format("用户注册 - 用户名: %s, 角色: %s, 结果: %s, IP: %s", 
            username, role, result, ipAddress);
        logSecurityEvent(action, username, result, message, ipAddress, userAgent);
    }

    /**
     * 记录密码修改操作
     */
    public static void logPasswordChange(String username, boolean success, String ipAddress, String userAgent) {
        String action = "PASSWORD_CHANGE";
        String result = success ? "SUCCESS" : "FAILED";
        String message = String.format("密码修改 - 用户名: %s, 结果: %s, IP: %s", username, result, ipAddress);
        logSecurityEvent(action, username, result, message, ipAddress, userAgent);
    }

    /**
     * 记录密码重置操作
     */
    public static void logPasswordReset(String username, boolean success, String ipAddress) {
        String action = "PASSWORD_RESET";
        String result = success ? "SUCCESS" : "FAILED";
        String message = String.format("密码重置 - 用户名: %s, 结果: %s, IP: %s", username, result, ipAddress);
        logSecurityEvent(action, username, result, message, ipAddress, null);
    }

    /**
     * 记录数据删除操作
     */
    public static void logDataDelete(String username, String dataType, Long dataId, String ipAddress, String userAgent) {
        String action = "DATA_DELETE";
        String message = String.format("数据删除 - 用户名: %s, 数据类型: %s, 数据ID: %s, IP: %s", 
            username, dataType, dataId, ipAddress);
        logSecurityEvent(action, username, "SUCCESS", message, ipAddress, userAgent);
    }

    /**
     * 记录权限变更操作
     */
    public static void logPermissionChange(String operator, String targetUser, String permission, String actionType, 
                                          String ipAddress, String userAgent) {
        String action = "PERMISSION_CHANGE";
        String message = String.format("权限变更 - 操作人: %s, 目标用户: %s, 权限: %s, 操作类型: %s, IP: %s", 
            operator, targetUser, permission, actionType, ipAddress);
        logSecurityEvent(action, operator, "SUCCESS", message, ipAddress, userAgent);
    }

    /**
     * 记录安全事件
     */
    private static void logSecurityEvent(String action, String username, String result, String message, 
                                        String ipAddress, String userAgent) {
        LocalDateTime now = LocalDateTime.now();
        
        // 使用MDC记录上下文信息
        MDC.put("action", action);
        MDC.put("username", username != null ? username : "ANONYMOUS");
        MDC.put("result", result);
        MDC.put("ip", ipAddress != null ? ipAddress : "UNKNOWN");
        MDC.put("timestamp", now.format(formatter));
        
        // 记录详细日志
        auditLogger.info("{} | {} | {} | {} | UserAgent: {}", 
            action, username != null ? username : "ANONYMOUS", result, message, 
            userAgent != null ? userAgent : "UNKNOWN");
        
        // 清理MDC
        MDC.clear();
    }

    /**
     * 从HttpServletRequest获取客户端IP
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多个IP的情况，取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip != null ? ip : "UNKNOWN";
    }

    /**
     * 从HttpServletRequest获取User-Agent
     */
    public static String getUserAgent(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return userAgent != null ? userAgent : "UNKNOWN";
    }
}

